package com.stylefeng.guns.wx.service;

import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.modular.customer.dao.ContactDao;
import com.stylefeng.guns.modular.customer.util.DataScopeUtil;
import com.stylefeng.guns.modular.customer.util.PinYinKit;
import com.stylefeng.guns.modular.system.model.Contact;
import com.stylefeng.guns.wx.transfer.WxContact;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WxContactService {

    @Autowired
    private ContactDao contactDao;

    public Map<String, List<WxContact>> list(Integer customerId, String name, Integer responsible) {
        List<Contact> contacts;
        if (responsible != null && 1 == responsible) {
            contacts = contactDao.selectContacts(DataScopeUtil.getResponsibleScope(), customerId, name);
        } else {
            contacts = contactDao.selectContacts(null, customerId, name);
        }

        return conv(contacts);
    }

    private Map<String, List<WxContact>> conv(List<Contact> contacts) {
        if (CollectionUtils.isEmpty(contacts)) {
            return Collections.EMPTY_MAP;
        }
        Map<String, List<WxContact>> map = new TreeMap<>();
        for (Contact contact : contacts) {
            WxContact wxContact = new WxContact();
            wxContact.setCustomerCompanyName(ConstantFactory.me().getCustomerCompanyName(contact.getCustomerCompanyId()));
            BeanKit.copyProperties(contact, wxContact);
            String firstChar = PinYinKit.getFirstChar(wxContact.getName());
            List<WxContact> wxContacts = map.get(firstChar);
            if (wxContacts == null) {
                wxContacts = new ArrayList<>();
                map.put(firstChar, wxContacts);
            }
            wxContacts.add(wxContact);
        }
        return map;
    }


}
